<template>
	<view class="weixin-login">
		<guide-popup ref="guidePopup" v-if="showGuide" :tipType="tipType" :showPhoneNumber="showPhoneNumber" :loginAccount="loginAccount" @cancel="autoLogin" @confirm="confirmGuide" @confirmGetPhoneNumber="confirmGetPhoneNumber" />
		<account-popup ref="accountPopup" v-if="showAcoount" :userAccounts="userAccounts" :defaultIndex="defaultIndex" @confirm="accountAutoLogin" @cancel="cancelGetPhoneNumber" @notLogin="setDefault" @confirmGetPhoneNumber="confirmGetPhoneNumber" />
		<tip-popup ref="tipPopup" v-if="showTip" :title="title" :cancelText="cancelText" :confirmText="confirmText" :showPhoneNumber="showPhoneNumber" :loginAccount="loginAccount" :content="msg" @confirm="confirmGuide" @cancel="autoLogin" @notLogin="setDefault"
			@confirmGetPhoneNumber="confirmGetPhoneNumber" />
	</view>
</template>
<script>
	import guidePopup from './guide-popup.vue'
	import accountPopup from './account-popup.vue'
	import tipPopup from './tip-popup.vue'
	import { getUserInfo, getUserWxInfo, getUserWxMobile, loginSync, checkBind, wxLogin } from '@/common/api/user.js'
	import { showModal, showCopy } from '@/common/hooks/useShow.js';
	import config from '@/uni.config.js';
	export default {
		name: 'weixin-login',
		props: {
			// 页面中接受的值
			// o:{
			// 	from:'m', //只要有值代表从其他端进入的
			// 	tmp_token: null, //只要有值，该值就是其他端登录所带过来的token
			// 	login_sync_token: null, //其他端没登录，login_sync_token就可以实现同步登录
			// }
			o: [Object],
			loginMsg: {
				type: [String],
				default: ''
			},
			title: {
				type: [String],
				default: '登录'
			},
			cancelText: {
				type: [String],
				default: '下次再说'
			},
			confirmText: {
				type: [String],
				default: '立即登录'
			},
			tipText: {
				type: [String],
				default: '立即登录'
			},
			loadType: { // 获取用户信息的时候请求，是否显示加载状态 0-不显示  1-显示  默认1
				type: [String, Number],
				default: 1
			},
			isShift: { //isShift=true&检测到只有一个账号&该账号绑定了手机号  满足三个条件直接返回执行登录
				type: [Boolean],
				default: false
			},
			loginGuide: { // 是否显示引导弹窗 不显示直接返回结果
				type: [Boolean],
				default: true
			}
		},
		components: {
			guidePopup,
			accountPopup,
			tipPopup
		},
		created() {
			uni.$once('loginLose', res => {
				this.loginLose();
			})
		},
		data() {
			return {
				flag: true,
				options: {},
				showGuide: false,
				showAcoount: false,
				showTip: false,
				userInfo: null,
				userAccounts: [],
				loginAccount: null,
				tipType: 1,
				showPhoneNumber: false,
				defaultIndex: 0,
				firstStep: true, //单账号的时候是否显示引导
				type: 'login',
				defaultLogin: true,
				parentMsg: '',
				msg: ''
			}
		},
		watch: {
			o: {
				deep: true,
				immediate: true,
				handler(val) {
					if (val) this.options = val;
				}
			},
			loginMsg: {
				deep: true,
				immediate: true,
				handler(val) {
					if (val) {
						this.parentMsg = val;
						this.msg = `${this.parentMsg}${this.tipText}`;
					}
				}
			}
		},
		methods: {
			setDefault() {
				this.flag = true;
				this.options = {};
				this.showGuide = false;
				this.showAcoount = false;
				this.showTip = false;
				this.userInfo = null;
				this.userAccounts = [];
				this.loginAccount = null;
				this.tipType = 1;
				this.showPhoneNumber = false;
				this.defaultIndex = 0;
				this.firstStep = true;
				this.type = 'login';
				this.defaultLogin = true;
				// this.msg = `${this.parentMsg}${this.tipText}`;
				this.msg = '';
				uni.hideLoading();
			},
			// 同步登录（页面级使用）
			async asyncLogin(token) {
				uni.showLoading({
					title: '登录中'
				});
				uni.$once('loginLose', res => {
					this.loginLose();
				});
				uni.setStorageSync('USER', { token: token });
				const res = await getUserInfo();
				if (res && res.data.mid) {
					uni.showToast({
						icon: 'success',
						title: '登录成功'
					})
					uni.setStorageSync('USER', { token: token, ...res.data });
					return res;
				}
			},
			async init() {
				if (!this.flag) return false;
				else this.flag = false;
				uni.showLoading({
					mask: true,
					title: '加载中'
				});
				let token = this.$store.getters.token;
				if (this.options.from && !this.options.tmp_token && !token) { // 其他端、小程序端都未登录
					this.defaultLogin = !this.loginGuide;
					return this.getWxInfo();
				} else if (this.options.from && this.options.tmp_token && !token) { // 其他端已经登录、小程序端都未登录
					this.defaultLogin = !this.loginGuide;
					return this.checkBind();
				} else if (token) {
					this.loginSuccess({ data: { token: token } });
				} else if (!this.options.from && !token) {
					return this.getWxInfo();
				}
			},
			async getWxInfo() {
				try {
					this.type = 'login';
					const code = await this.getCode();
					const res = await this.getUserWxInfo({ code: code, loadType: this.loadType });
					this.userInfo = res.data;
					this.userAccounts = res.data.all_user_info;
					this.tipType = this.userAccounts.length == 0 ? 1 : 2;
					if (this.isShift && this.userAccounts.length == 1 && this.userAccounts[0].checkmobile == 1) return res.data;
					this.showPhoneNumber = this.userAccounts.length == 0;
					if (this.userAccounts.length == 1 && !JSON.parse(this.userAccounts[0].checkmobile)) { // 单账号且没绑定手机号
						this.showPhoneNumber = true;
						this.loginAccount = this.userAccounts[0];
						this.msg = `${this.parentMsg}授权登录`;
					} else if (this.userAccounts.length == 1 && JSON.parse(this.userAccounts[0].checkmobile)) {
						if (!this.defaultLogin) {
							if (this.firstStep) this.openGuide();
							else this.autoLogin();
							return false;
						}
					}
					if (!this.loginGuide) return {
						showPhoneNumber: this.showPhoneNumber,
						loginAccount: this.loginAccount,
						userAccounts: this.userAccounts
					}
					if (!this.defaultLogin) this.openGuide();
					else if (this.defaultLogin && this.msg) this.openTip();
					else if (this.userAccounts.length == 1) {
						this.msg = `请先登录，点击${this.tipText}`;
						this.openTip();
					} else this.confirmGuide();
				} catch (e) {
					this.flag = true;
				}
			},
			// 同意引导
			async confirmGuide() {
				switch (this.type) {
					case 'login':
						if (this.userAccounts.length == 1) { // 单账号
							this.autoLogin();
						} else if (this.userAccounts.length > 1) { // 多账号
							this.openAccount();
						}
						break;
					case 'bind':
						await this.wxLogin({ parameter: { tmp_token: this.options.tmp_token, weixin_info: this.userInfo.weixin_info }, type: this.type });
						break;
				}
			},
			// 拒绝/关闭引导等后自动登录
			async autoLogin() {
				switch (this.type) {
					case 'login':
						if (this.userAccounts.length == 0) { // 无账号就用微信信息注册
							await this.wxLogin({ parameter: { weixin_info: this.userInfo.weixin_info }, type: this.type });
						} else if (this.userAccounts.length == 1) { // 只有一个账号
							await this.wxLogin({ parameter: { mid: this.userAccounts[0].mid, weixin_info: this.userInfo.weixin_info }, type: this.type });
						}
						break;
					case 'bind':
						await this.wxLogin({ parameter: { tmp_token: this.options.tmp_token, weixin_info: this.userInfo.weixin_info }, type: this.type });
						break;
				}
			},
			// 用户选择了账号后等操作后的自动登录处理
			async accountAutoLogin(data) {
				switch (this.type) {
					case 'login':
						await this.wxLogin({ parameter: { mid: data.mid, weixin_info: this.userInfo.weixin_info }, type: this.type });
						break;
					case 'bind':
						await this.wxLogin({ parameter: { tmp_token: this.options.tmp_token, weixin_info: this.userInfo.weixin_info }, type: this.type });
						break;
				}
			},
			// 拒绝手机号授权
			cancelGetPhoneNumber() {
				uni.showToast({
					icon: 'none',
					title: '拒绝手机号授权'
				})
				this.setDefault();
			},
			// 同意手机号授权
			async confirmGetPhoneNumber(data) {
				const getWxMobileRes = await getUserWxMobile(data.parameter);
				switch (this.type) {
					case 'login':
						const mid = data.mid;
						const parameter = mid ? { mobile: getWxMobileRes.data.mobile, mid, weixin_info: this.userInfo.weixin_info } : { mobile: getWxMobileRes.data.mobile, weixin_info: this.userInfo.weixin_info }
						await this.wxLogin({ parameter: parameter, type: this.type });
						break;
					case 'bind':
						await this.wxLogin({ parameter: { mobile: getWxMobileRes.data.mobile, tmp_token: this.options.tmp_token, weixin_info: this.userInfo.weixin_info }, type: this.type });
						break;
				}
			},
			// 打开引导
			openGuide() {
				this.showGuide = true;
				setTimeout(() => {
					this.$refs.guidePopup.open();
				}, 200)
			},
			// 打开选择账号
			openAccount() {
				this.showAcoount = true;
				setTimeout(() => {
					this.$refs.accountPopup.open();
				}, 200)
			},
			// 检测其他端过来的账号是否绑定手机号
			async checkBind() {
				this.type = 'bind';
				const req = checkBind({ tmp_token: this.options.tmp_token });
				const res = await req;
				if (res.data.is_bind_mobile && res.data.is_bind_weixin) {
					// this.setDefault(); // 非其他端的默认方式
					this.getWxInfo();
					return false;
				}
				const code = await this.getCode();
				const userInfoRes = await this.getUserWxInfo({ code: code, loadType: this.loadType });
				this.userInfo = userInfoRes.data;
				this.userAccounts = userInfoRes.data.all_user_info;
				this.tipType = this.userAccounts.length == 0 ? 1 : 2;
				if (!res.data.is_bind_mobile && !res.data.is_bind_weixin) { //未绑定手机号，未绑定微信
					this.showPhoneNumber = true;
					if (this.loginGuide) this.openGuide();
				} else if (res.data.is_bind_mobile && !res.data.is_bind_weixin) { //绑定了手机号，未绑定微信
					if (this.loginGuide) {
						if (this.firstStep) this.openGuide();
						else this.autoLogin();
					}
				} else if (!res.data.is_bind_mobile && res.data.is_bind_weixin) { //未绑定手机号，已绑定了微信
					this.showPhoneNumber = true;
					if (this.loginGuide) this.openGuide();
				}
				if (!this.loginGuide) return {
					showPhoneNumber: this.showPhoneNumber
				}
			},
			// 打开提示
			openTip() {
				this.showTip = true;
				setTimeout(() => {
					this.$refs.tipPopup.open();
				}, 200)
			},
			// 获取code
			async getCode() {
				const res = await uni.login({ provider: 'weixin' });
				return res.code;
			},
			// 登录失效处理
			async loginLose() {
				// if (!this.loginGuide) return uni.showToast({
				// 	icon: 'none',
				// 	title: 'token失效，请重新上一步操作进行登录'
				// })
				// this.setDefault();
				// await this.$store.dispatch('user/loginOut');
				// this.msg = '登录失效，请重新登录';
				// this.init();
			},
			// 获取用户账号及对应的unionid等信息
			async getUserWxInfo(data) {
				const userInfoRes = await uni.getUserInfo({ provider: 'weixin' });
				if (userInfoRes.errMsg != 'getUserInfo:ok') {
					return uni.showModal({
						content: `获取用户信息失败：${JSON.stringify(userInfoErr||userInfoRes.errMsg)}`,
						showCancel: false
					})
				}
				const iv = userInfoRes.iv;
				const encryptedData = userInfoRes.encryptedData;
				try {
					const loadType = data.loadType ? data.loadType : 0;
					const getWxInfoReq = getUserWxInfo({ code: data.code, iv: iv, ciphertext: encryptedData }, loadType);
					const getWxInfoRes = await getWxInfoReq;
					// ================测试===================
					// getWxInfoRes.data.all_user_info = [getWxInfoRes.data.all_user_info[1]]
					// getWxInfoRes.data.all_user_info = []
					// getWxInfoRes.data.all_user_info.splice(0,1);
					return getWxInfoRes;
				} catch (e) {
					await Promise.reject(e);
				}
			},
			// 微信小程序执行登录
			async wxLogin(data) {
				try {
					const req = wxLogin({ ...data.parameter }, data.type);
					const res = await req;
					this.$store.commit('user/SET_TOKEN', { token: res.data.token });
					await this.$store.dispatch('app/init');
					if (!this.notBindMobile()) return;
					this.loginSuccess(res);
					return res;
				} catch (e) {
					await Promise.reject('登录失败');
				}
			},
			// 未绑定手机号提示
			notBindMobile() {
				if (!this.$store.getters.userInfo?.mobile) {
					uni.hideToast();
					this.setDefault();
					showModal({
						title: '提示',
						content: `该手机号已被其他账号绑定，请使用其他手机号进行绑定。如需帮助请联系QQ：${config.customer.qq_operate}`,
						confirmText: '我知道了',
						cancelText: '复制QQ',
						cancel() {
							showCopy({
								data: config.customer.qq_operate,
								type: 1,
								icon: 'none',
								title: `QQ号已复制`
							})
						}
					})
					this.$store.commit('user/REMOVE_TOKEN');
					return false;
				}
				return true;
			},
			// 登录成功
			async loginSuccess(loginRes) {
				if (this.options.from && !this.options.tmp_token && this.options.login_sync_token && loginRes && loginRes.data.token) {
					const req = loginSync({ login_sync_token: this.options.login_sync_token });
					await req;
				}
				uni.showToast({
					icon: 'success',
					title: '登录成功'
				})
				this.$emit('loginSuccess');
				// if (loginRes && loginRes.data.token) {
				// 	uni.$emit('loginSuccess', loginRes);
				// } else {
				// 	this.$store.dispatch('user/loginOut');
				// }
				this.setDefault();
			}
		}
	}
</script>
